import { ref, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

export function useForm(props, emits) {
  const searchForm = ref() // 表单ref
  const toggle = ref(true) // 展开收起状态
  const form = computed(() => props.initForm)
  const loading = ref(false)

  const formItems = computed(() => {
    if (toggle.value) {
      return props.formList
    }
    return props.formList.filter((item, index) => index < 4)
  })

  const toggleStatus = () => (toggle.value = !toggle.value)
  const onSubmit = () => {
    if (loading.value) {
      return false
    }
    loading.value = true
    searchForm.value.validate(async (valid) => {
      if (valid) {
        if (!props.api) {
          loading.value = false
          return ElMessage({
            message: 'useForm必传参数api不能为空',
            type: 'error'
          })
        }
        await onSearch()
      } else {
        loading.value = false
        return ElMessage({
          message: '参数校验不通过,请检查',
          type: 'error'
        })
      }
    })
  } // 提交表单
  const onReset = () => {
    if (loading.value) {
      return false
    }
    searchForm.value.resetFields()
    onSubmit()
  } // 重置表单

  const onSearch = async () => {
    const params = {}
    Object.keys(form.value).forEach((key) => {
      if (form.value[key]) {
        params[key] = form.value[key]
      }
    })
    const response = await window.$apis[props.api](params).finally(() => {
      loading.value = false
    })
    emits('getResponse', response)
  }

  onMounted(() => {
    onSubmit()
  })

  return {
    searchForm,
    form,
    toggle,
    formItems,
    toggleStatus,
    onSubmit,
    onReset
  }
}
